import { App } from "vue";
import { useLoginStore } from "/@ts/store/modules/login";

/**
 * 挂载到vue实例函数
 * @param app vue实例
 */
export function setupDirectivePage(app: App<Element>) {
  app.directive("hasPermi", {
    mounted(el, binding) {
      const loginModule = useLoginStore();
      const { value } = binding;
      const all_permission = "*:*:*";
      const permissions = loginModule.getPermissions;

      if (value && value instanceof Array && value.length > 0) {
        const permissionFlag = value;

        const hasPermissions = permissions.some((permission: any) => {
          return (
            all_permission === permission || permissionFlag.includes(permission)
          );
        });
        if (!hasPermissions) {
          el.parentNode && el.parentNode.removeChild(el);
        }
      } else {
        throw new Error(`请设置操作权限标签值`);
      }
    },
  });

  app.directive("isSelf", {
    beforeMount(el, binding) {
      el.clickOutsideEvent = function (event: any) {
        // 检查点击事件是否发生在当前元素之外
        if (!(el === event.target || el.contains(event.target))) {
          binding.value();
        }
      };
      document.body.addEventListener("click", el.clickOutsideEvent);
    },
    unmounted(el) {
      document.body.removeEventListener("click", el.clickOutsideEvent);
    },
  });
}
